const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
// const koaCors=require('koa2-cors')
const koaCors=require('@koa/cors')
const koaCookie=require('koa-cookie').default
const koaJWT=require('koa-jwt')

const sequelize=require('./db/index')
const index = require('./routes/index')
const users = require('./routes/users')
const login = require('./routes/login')
const home = require('./routes/home')
const project = require('./routes/project')

// error handler
onerror(app)

// middlewares
// app.use(
//   koaJWT({
//     // secret密钥，解密
//     secret:'test and verify'
//   }).unless({
//     // unless以下地址不需要通过jwt验证
//     path:[/^\/login/,/^\/register/]
//   })
// )

app.use(koaCors(
  // origin前端页面地址
  // credentials cookie是否可以写入
  {
    origin:'http://localhost:5173',
    credentials:true
  }
))
// app.use(koaCors())

app.use(koaCookie())
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(login.routes(), login.allowedMethods())
app.use(home.routes(), home.allowedMethods())
app.use(project.routes(), project.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
